package com.manageserver.service.Impl;

import com.managecommon.result.Result;
import com.managepojo.entity.LoginUser;
import com.managepojo.entity.ResponseResult;
import com.managepojo.entity.User;
import com.manageserver.service.LoginService;
import com.manageserver.utils.JwtUtil;
import com.manageserver.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author Godfrey
 * @description
 * @Date 2023/7/14 17:11
 * @Version 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        //将用户登录时的账号，密码封装成UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证未通过，则直接抛出异常
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        //认证通过，用userId生成jwt，并将其返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        redisCache.setCacheObject("login" + userId, loginUser);
        return new ResponseResult(200, "登录成功", map);
    }

    /**
     * 退出
     *
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的userid
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userId = loginUser.getUser().getUserId();
        //从redis中删除对应的token
        redisCache.deleteObject("login" + userId);
        return new ResponseResult(200, "注销成功");
    }
}
